package com.jiyinit.web.core.mobile.controller;

import java.text.ParseException;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.web.core.business.dto.TaskUrgeRequest;
import com.jiyinit.web.core.business.enums.OperationTypeConstant;
import com.jiyinit.web.core.business.enums.SystemConstant;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.common.util.MessagePush;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.TaskRequest;
import com.jiyinit.web.core.business.entity.TabCoreTask;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.service.TaskServiceImpl;
import com.jiyinit.web.core.business.service.UserTaskServiceImpl;
import com.jiyinit.web.core.business.vo.TaskInfoVo;
import com.jiyinit.web.core.business.vo.UserTaskVo;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.logic.ValidateResult;
import com.jiyinit.web.core.common.util.DateUtil;
import com.jiyinit.web.core.common.util.UserUtil;

/**
 * 用户管理
 *
 * @author wuyuefeng
 * @version 1.0
 * @date 2017/4/13 9:01
 * @since 1.0
 */
@Controller
@RequestMapping("/mobile/mtask")
public class MtaskController {
	/**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MtaskController.class);
    
    @Resource(name = "core.taskServiceImpl")
    private TaskServiceImpl taskServiceImpl;
    @Resource(name = "core.userTaskServiceImpl")
    private UserTaskServiceImpl userTaskServiceImpl;
    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;
    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;
    /**
     * 跳转到查询任务信息页面
     *
     * @param request
     * @return
     */
    @RequestMapping("/test")
    public String toFindtest(HttpServletRequest request) {
        return "/task/test";
    }
    /**
     * 跳转到查询任务信息页面
     *
     * @param request
     * @return
     */
    @RequestMapping("/findTasks")
    public String toFindUserList(HttpServletRequest request) {
        return "/task/tasks";
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月3日 上午10:18:37
         * @param 
         * @return
     */
    @RequestMapping("/findMyTasks")
    public String FindMyList(HttpServletRequest request) {
        return "/task/mytasks";
    }
    
    /**
     * 按条件查询用户信息
     *
     * @param request
     * @return
     */
   
    @RequestMapping(method = RequestMethod.POST, value = "/mfindByPage")
    @ResponseBody
    public ResponseEntity<ResponseDto> findByPage(HttpServletRequest request) {
//    	taskRequest.setLimit(10);
//    	taskRequest.setCreateUid(UserUtil.getCurrentUser().getUserId());
    	TaskRequest taskRequest = this.getJsonToTaskRequest(request);
        PagingResult<TaskInfoVo> pagingResult = taskServiceImpl.findTasksByCons(taskRequest);
        LogUtil.info(LOGGER, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(),pagingResult.getRows());
        if(pagingResult != null)
        	return new ResponseEntity<>(ResponseDto.responseOK(pagingResult), HttpStatus.OK);
        return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
    }
    /**
     * 
         * 说明我参与的或者我发布的
         * @author wuyuefeng
         * @create 2017年5月3日 上午10:18:55
         * @param 
         * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/mfindMyAllTasks")
    @ResponseBody
    public ResponseEntity<ResponseDto> findMyAllTasks(HttpServletRequest request) {
//    	taskRequest.setLimit(10);
    	TaskRequest taskRequest = this.getJsonToTaskRequest(request);
    	taskRequest.setAlloterId(taskRequest.getAlloterId());
        PagingResult<TaskInfoVo> pagingResult = taskServiceImpl.findTasksAndAlloters(taskRequest);
        LogUtil.info(LOGGER, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(),pagingResult.getRows());
        if(pagingResult != null)
        	return new ResponseEntity<>(ResponseDto.responseOK(pagingResult), HttpStatus.OK);
        return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
    }
    
    /**
     * 
         * 说明全部任务
         * @author wuyuefeng
         * @create 2017年5月3日 上午10:18:55
         * @param 
         * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/mfindAllMyTasks")
    @ResponseBody
    public ResponseEntity<ResponseDto> findAllMyTasks(HttpServletRequest request) {
    	TaskRequest taskRequest = this.getJsonToTaskRequest(request);
    	//taskRequest.setAlloterId(taskRequest.getAlloterId());
        PagingResult<TaskInfoVo> pagingResult = taskServiceImpl.findAllMyTasks(taskRequest);
        //LogUtil.info(LOGGER, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(),pagingResult.getRows());

        //不在主页面显示交流园地
        ArrayList<TaskInfoVo> tasks = new ArrayList<>();
        List<TaskInfoVo> list = pagingResult.getRows();
        for (int i = 0; i <list.size(); i++) {
            TaskInfoVo task = list.get(i);
            if(task.getTaskCla().intValue() != 77){
                tasks.add(list.get(i));
            }
        }
        pagingResult.setRows(tasks);
        if(pagingResult != null)
        	return new ResponseEntity<>(ResponseDto.responseOK(pagingResult), HttpStatus.OK);
        return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
    }
    
    
    /**
     * 跳到新增页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/add")
    public String add(HttpServletRequest request,TaskRequest taskRequest) {
    	request.setAttribute("taskPid", taskRequest.getTaskId());
    	request.setAttribute("taskPname", taskRequest.getTitle());
    	request.setAttribute("taskPuid", taskRequest.getTaskPuid());
    	
    	Integer userId = UserUtil.getCurrentUser().getUserId();
    	
    	List<UserTaskVo> userTaskVos = new ArrayList<UserTaskVo>();
    	userTaskVos = userTaskServiceImpl.findUserRolls(userId);
    	request.setAttribute("userTaskVos", userTaskVos);
    	
        return "/task/add";
    }
    
    
    /**
     * 新增任务
     *
     * @param request
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/maddTask")
    public ResponseEntity<ResponseDto> save(HttpServletRequest request) {
    	
    	TaskRequest taskRequest = getJsonToTaskRequest(request);
    	
    	Integer alloterId = 0;
    	double plDays = 0.0;
		DateUtil std = new DateUtil();
        // 校验参数
        ValidateResult<TaskRequest> validateResult = paramCheckLogic.checkParamValidate(taskRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        
        TabCoreTask tabCoreTask = new TabCoreTask();
        BeanUtils.copyProperties(taskRequest, tabCoreTask);
       
        tabCoreTask.setStatus("0");
        
        tabCoreTask.setCreateTime(new Date());
        tabCoreTask.setEditTime(new Date());
        //tabCoreTask.setCreateUid(UserUtil.getCurrentUser().getUserId());
        //tabCoreTask.setCreateUid(createUid);
        
        Date startTime = tabCoreTask.getStartTimePl();
        Date endTime = tabCoreTask.getEndTimePl();
        try {
        	plDays = (double)std.daysBetween(startTime,endTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
        
        tabCoreTask.setPlDays(plDays+1);
        
        tabCoreTask.setIsDel(new Integer(0));
        //添加分配人
        alloterId = taskRequest.getAlloterId();
        
        Integer[] userIdss = taskRequest.getAlloterIds();

        tabCoreTask.setTaskCla(SystemConstant.SIMPLE_TASK);

    	int num = 0;
    	if(userIdss != null && userIdss.length!=0){
    		num = taskServiceImpl.addTaskAndUser(tabCoreTask,userIdss,taskRequest, OperationTypeConstant.TASK_ADD);
    	}else{
    		num = taskServiceImpl.addTask(tabCoreTask);
    	}
        
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("faild"), HttpStatus.OK);
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年4月25日 下午5:49:23
         * @param 
         * @return
     */
    @RequestMapping(value = "/mupdate")
    public ResponseEntity<ResponseDto> taskModify(HttpServletRequest request) {
    	TaskRequest taskRequest = getJsonToTaskRequest(request);
    	TabCoreTask tabCoreTask = taskServiceImpl.findTaskById(taskRequest.getTaskId());
    	if(tabCoreTask!=null)
    		return new ResponseEntity<>(ResponseDto.responseOK(tabCoreTask), HttpStatus.OK);
    	return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月3日 下午4:24:49
         * @param 
         * @return
     */
    @RequestMapping(value = "/complete")
    public String taskComplete(HttpServletRequest request, Integer taskId) {
    	TabCoreTask tabCoreTask = taskServiceImpl.findTaskById(taskId);
        request.setAttribute("tabCoreTask", tabCoreTask);
        return "/task/complete";
    }
    
    /**
     * t
         * 说明
         * @author wuyuefeng
         * @create 2017年4月26日 下午2:43:22
         * @param 
         * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/mupdateTask")
    public ResponseEntity<ResponseDto> updateTask(HttpServletRequest request) {
    	
    	TaskRequest taskRequest = getJsonToTaskRequest(request);
    	
    	String complete = taskRequest.getComplete();
    	TabCoreTask tabCoreTask = taskServiceImpl.findTaskById(taskRequest.getTaskId());
    	DateUtil std = new DateUtil();
    	if(null == complete || complete.equals("")){
    	
	        // 校验参数
			double plDays = 0.0;
	    	ValidateResult<TaskRequest> validateResult = paramCheckLogic.checkParamValidate(taskRequest);
	        if (!validateResult.isSuccess()) {
	            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
	        }


            Date createTime=tabCoreTask.getCreateTime();
	        BeanUtils.copyProperties(taskRequest, tabCoreTask);
            tabCoreTask.setCreateTime(createTime);
	        tabCoreTask.setDescription(taskRequest.getTaskDesc());
	        
	        
	        tabCoreTask.setEditTime(new Date());
	        
	        if(tabCoreTask.getCreateUid()==null||tabCoreTask.getCreateUid()==0){
	        	tabCoreTask.setCreateUid(UserUtil.getCurrentUser().getUserId());
	        }
	        
	       
	        
	        
	        Date startTimeReal = tabCoreTask.getStartTimeReal();
	        Date endTimeReal = tabCoreTask.getEndTimeReal();
	        double realDays = 0.0;
	        if(startTimeReal !=null && endTimeReal !=null){
	        	try {
	        		realDays = (double)std.daysBetween(startTimeReal,endTimeReal);
	    		} catch (ParseException e) {
	    			e.printStackTrace();
	    		}
	        	tabCoreTask.setRealDays(realDays+1);
	        }
	        Date startTime = tabCoreTask.getStartTimePl();
	        Date endTime = tabCoreTask.getEndTimePl();
	        try {
	        	plDays = (double)std.daysBetween(startTime,endTime);
			} catch (ParseException e) {
				e.printStackTrace();
			}
	        
	        tabCoreTask.setPlDays(plDays+1);
	        
	        
	        tabCoreTask.setIsDel(new Integer(0));
    	}else{
    		//任务完成
    		tabCoreTask.setStatus("1");
    		tabCoreTask.setEditTime(new Date());
    		Date startTimeReal = tabCoreTask.getStartTimeReal();
	        Date endTimeReal = tabCoreTask.getEndTimeReal();
	        
	        double realDays = 0.0;
	        if(startTimeReal !=null && endTimeReal !=null){
	        	try {
	        		realDays = (double)std.daysBetween(startTimeReal,endTimeReal);
	    		} catch (ParseException e) {
	    			e.printStackTrace();
	    		}
	        	tabCoreTask.setRealDays(realDays+1);
	        }
	        
    	}
    	
    	Integer[] userIdss = taskRequest.getAlloterIds();
         
     	int num = 0;
     	if(userIdss != null && userIdss.length!=0){
     		num = taskServiceImpl.addTaskAndUser(tabCoreTask,userIdss,taskRequest,OperationTypeConstant.TASK_CHANGE_PERSON);}
        else {
            num = taskServiceImpl.updateTask(tabCoreTask);
            //return new ResponseEntity<>(ResponseDto.responseFail("请至少指定一个参与人"), HttpStatus.OK);
        }

        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
    }
    
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年4月26日 下午2:43:35
         * @param 
         * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/mdelete")
    public ResponseEntity<ResponseDto> delete(HttpServletRequest request) {
    	String logJson = request.getParameter("request_json");
    	LogUtil.info(LOGGER, "logJson:{}", logJson);
    	TaskRequest taskRequest = getJsonToTaskRequest(request);
    	
    	Integer[] taskIds = taskRequest.getTaskIds();
    	
    	LogUtil.info(LOGGER, "taskIds:{}", taskIds);
        
        String isOk = taskServiceImpl.deleteTask(taskIds);
        if (null != isOk) {
        	if(isOk.equals("distribute")){
        		return new ResponseEntity<>(ResponseDto.responseFail("该任务已分解，不能删除！"), HttpStatus.OK);
        	}else if(isOk.equals("child")){
        		return new ResponseEntity<>(ResponseDto.responseFail("该任务已分配，不能删除！"), HttpStatus.OK);
        	}else if(isOk.equals("ok")){
        		return new ResponseEntity<>(ResponseDto.responseOK("ok"), HttpStatus.OK);
        	}else{
        		return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
        	}
        }
        return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
    }
    
    
    /**
     * 
         * 跳转任务分配页面
         * @author wuyuefeng
         * @create 2017年4月27日 上午9:35:02
         * @param 
         * @return
     */
    @RequestMapping("/taskAllot")
    public String toTaskAllot() {
        return "/task/taskAllot";
    }
    /**
     * 
         * 任务分配选择人员
         * @author wuyuefeng
         * @create 2017年4月27日 上午9:20:17
         * @param 
         * @return
     */
    
    
    @RequestMapping("/toOrgTree")
    public String toTreeMenu() {
        return "/task/orgTree";
    }
    
 
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月4日 下午3:17:06
         * @param 
         * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/checkTitle")
    public ResponseEntity<ResponseDto> checkTitle(HttpServletRequest request,String title) {
        LogUtil.info(LOGGER, "title:{}", title);
        List<TabCoreTask> tabCoreTasks = taskServiceImpl.findTaskByTitle(title);
        if(tabCoreTasks.size() >= 1){
        	return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
            
        }
        return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
    }
    
    
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月12日 上午8:49:48
         * @param 
         * @return
     */
    @RequestMapping("/message")
    public String toTaskMessage(HttpServletRequest request,Integer taskId) {
    	
        return "/task/message";
    }
    
    @RequestMapping("/toTest")
    public String toTest() {
        return "/task/test";
    }
    
    
    private TaskRequest getJsonToTaskRequest(HttpServletRequest request){
    	String logJson = request.getParameter("request_json");
    	LogUtil.info(LOGGER, "logJson:{}", logJson);
    	TaskRequest taskRequest = (TaskRequest)JsonEntityTransform.json2Object(logJson, TaskRequest.class);
    	return taskRequest;
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/taskUrge")
    public ResponseEntity<ResponseDto> TaskUrge(HttpServletRequest request) {
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        TaskUrgeRequest taskUrgeRequest = JsonEntityTransform.json2Object(logJson, TaskUrgeRequest.class);
        if(Check.isNullStr(taskUrgeRequest.getTaskId()))
        {
            return new ResponseEntity<>(ResponseDto.responseFail("任务ID不能为空"), HttpStatus.OK);
        }
        if(Check.isNullStr(taskUrgeRequest.getUserId()))
        {
            return new ResponseEntity<>(ResponseDto.responseFail("催办人ID不能为空"), HttpStatus.OK);
        }
        if(Check.isNullStr(taskUrgeRequest.getToUserId()))
        {
            return new ResponseEntity<>(ResponseDto.responseFail("被催办人ID不能为空"), HttpStatus.OK);
        }
        TabCoreTask task=taskServiceImpl.findTaskById(Integer.parseInt(taskUrgeRequest.getTaskId()));
        if(Check.isNullObj(task))
        {
            return new ResponseEntity<>(ResponseDto.responseFail("任务ID无效"), HttpStatus.OK);
        }
        TabCoreUserEntity user=userService.getUserInfoByUserId(Integer.parseInt(taskUrgeRequest.getUserId()));
        if(Check.isNullObj(user))
        {
            return new ResponseEntity<>(ResponseDto.responseFail("催办人ID无效"), HttpStatus.OK);
        }
        TabCoreUserEntity toUser=userService.getUserInfoByUserId(Integer.parseInt(taskUrgeRequest.getToUserId()));
        if(Check.isNullObj(toUser))
        {
            return new ResponseEntity<>(ResponseDto.responseFail("被催办人ID无效"), HttpStatus.OK);
        }
        //极光推送
        Map<String,String> returnStr = new HashMap<>();
        returnStr.put("taskId",String.valueOf(task.getTaskId()));
        returnStr.put("title",task.getTitle());
        returnStr.put("userId",String.valueOf(user.getUserId()));
        returnStr.put("createUid",String.valueOf(task.getCreateUid()));
        returnStr.put("toUserId",String.valueOf(toUser.getUserId()));
        returnStr.put("type", OperationTypeConstant.TASK_URGE);
        returnStr.put("content",user.getUserName()+"催促您办理任务:"+task.getTitle());
        String[] sendUsers=new String[]{String.valueOf(toUser.getUserId())};
        MessagePush messagePush = new MessagePush(returnStr,sendUsers);

        return new ResponseEntity<>(ResponseDto.responseOK("催办成功"), HttpStatus.OK);
    }

    /**
     * 根据我发布、我参与、待办、已办、临期和逾期等条件组合筛选任务数据
     * @author liuzongguang
     * @create 2018/10/23 17:38
     */
    @RequestMapping(method = RequestMethod.POST, value = "/mfindTasksByConditions")
    @ResponseBody
    public ResponseEntity<ResponseDto> findTasksByConditions(HttpServletRequest request) {
        TaskRequest taskRequest = this.getJsonToTaskRequest(request);
        PagingResult<TaskInfoVo> pagingResult = taskServiceImpl.findTasksByConditions(taskRequest);
        if(pagingResult != null)
            return new ResponseEntity<>(ResponseDto.responseOK(pagingResult), HttpStatus.OK);
        return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
    }
}
